package itheima.reggie.Filter;

import com.alibaba.fastjson.JSON;
import itheima.reggie.common.R;
import itheima.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查是否已经登录
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持统配附
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //获取请求的ip
        String remoteAddr = request.getRemoteAddr();
        log.info("该地址发起请求："+remoteAddr);
        //获取本次请求的url
        String requestURI=request.getRequestURI();
        log.info("拦截到请求：{}",request.getRequestURI());
        //不需要处理的请求路径
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //匹配路径
        boolean check=check(urls,requestURI);
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //判断登录状态 后台
        Long id=(Long) request.getSession().getAttribute("employee");
        if (id!=null){
            log.info("拦截到请求：{}",request.getRequestURI());
            log.info("用户：{}已登录",id);
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,response);
            return;
        }
        //判断登录状态 移动端
        if (request.getSession().getAttribute("user")!=null){
            log.info("拦截到请求：{}",request.getRequestURI());
            Long userId=(Long) request.getSession().getAttribute("user");
            log.info("用户：{}已登录",userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截一次非法请求！路径:{}",requestURI);


    }

    @Override
    public void destroy() {

    }

    /**
     * 检查是否放行
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url:urls){
            boolean match=PATH_MATCHER.match(url,requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
